package com.awspaas.user.apps.shhtaerospaceindustrial.healthmeaasge;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.schedule.IJob;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.BOAPI;
import com.actionsoft.sdk.local.api.ProcessAPI;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.awspaas.user.apps.shhtaerospaceindustrial.util.CoreUtil;

public class DrugDataSynchronous implements IJob {

	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		// TODO Auto-generated method stub
		String strs =healthCheckDrugs("",1);
		if("11".equals(strs)) {
			System.out.println("数据鉴权失败！！！");
		}else if("22".equals(strs)){
			System.out.println("获取数据失败！！！");
		}else {
			Result(strs);
			System.out.println("同步药品数据成功！！！");
		}
	}
	//同步药品数据
	public void Result(String strs) {
	 	JSONObject jsonObject= JSONObject.parseObject(strs);
        JSONArray jsonArray = (JSONArray)jsonObject.get("yps");
       
        for (int i = 0; i < jsonArray.size(); i++) {
    		BO zghead = new BO();
	       	JSONObject jsonObject2 = (JSONObject)jsonArray.get(i);
	       	String ORGNAME = CoreUtil.objToStr(jsonObject2.get("ORGNAME"));// 网格点
	       	String ITEMID = CoreUtil.objToStr(jsonObject2.get("ITEMID"));// 商品编号
	       	String ITEMNAME =CoreUtil.objToStr( jsonObject2.get("ITEMNAME"));//药品名
	       	String ENTNAME = CoreUtil.objToStr(jsonObject2.get("ENTNAME"));// 生产厂家
	       	String ITEMSPEC = CoreUtil.objToStr(jsonObject2.get("ITEMSPEC"));// 规格
	       	String YKBZPRICE = CoreUtil.objToStr(jsonObject2.get("YKBZPRICE"));// 单价
	       	String YKBZUNIT = CoreUtil.objToStr(jsonObject2.get("YKBZUNIT"));// 包装单位
	       	String NUM = CoreUtil.objToStr(jsonObject2.get("NUM"));// 数量
	       	if(!"".equals(ORGNAME) && !"".equals(ITEMID)) {
	       		String sqlId ="select id  from BO_EU_DRUGLIBRARY  where WGDNAME='"+ORGNAME+"' and DRUGNUM ='"+ITEMID+"'";
		        String drugid =CoreUtil.objToStr(DBSql.getString(sqlId,"id"));
		        if(!"".equals(drugid) ) {
		       		zghead.set("DRUGNAME",ITEMNAME);//药品名称
		       		zghead.set("MANUFACTURER",ENTNAME);//生产厂家
		       		zghead.set("DRUGSPEC",ITEMSPEC);//药品规格
		       		zghead.set("DRUGPRICE",YKBZPRICE);//药品单价
		       		zghead.set("DRUGUNIT",YKBZUNIT);//药品单位
		       		zghead.set("NUM",NUM);//数量
		        	zghead.set("ID",drugid);//id
		        	////更新数据
		        	SDK.getBOAPI().update("BO_EU_DRUGLIBRARY", zghead);
		        	
		        }else {
		        	List<BO> insertdatahead = new ArrayList<BO>();//插入数据
		        	zghead.set("WGDNAME",ORGNAME);//网格点名称
		       		zghead.set("DRUGNUM",ITEMID);//药品编码
		       		zghead.set("DRUGNAME",ITEMNAME);//药品名称
		       		zghead.set("MANUFACTURER",ENTNAME);//生产厂家
		       		zghead.set("DRUGSPEC",ITEMSPEC);//药品规格
		       		zghead.set("DRUGPRICE",YKBZPRICE);//药品单价
		       		zghead.set("DRUGUNIT",YKBZUNIT);//药品单位
		       		zghead.set("NUM",NUM);//数量
		       		zghead.set("STATE","是");//启用状态
		       		insertdatahead.add(zghead);
		       		String kp_prosid = "obj_750d26e9abab4cdeb3e9198ca633af42";
		       		ProcessAPI proapi = SDK.getProcessAPI();
		       		ProcessInstance processinstance =proapi.createBOProcessInstance(kp_prosid, "admin", "药品库维护");
					BOAPI boapi = SDK.getBOAPI();
					boapi.create("BO_EU_DRUGLIBRARY", insertdatahead,processinstance, null);
		        }
	       	}
       }
}
	//数据鉴权
	public  HealthLoginResult login() {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        String name = "JPurRkTCBFD142Iv";
        String password = "pJmWgOP2IdtDNDBsrxfdc995hN2oh5u9";
        long time = System.currentTimeMillis() / 1000;
        String hash = new Sha256Hash("username=" + name + "&password=" + password + "&time=" + time).toHex();
        int index = (int) time % 64;
        String md5Hex = DigestUtils.md5Hex(hash.substring(index) + hash.substring(0, index));
        param.add("username", name);
        param.add("password", md5Hex);
        param.add("time", time);
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, Object>> multiValueMapHttpEntity = new HttpEntity<>(param, headers);
        String url = "https://api.wx738.com/api/login";
        ResponseEntity<String> response = restTemplate.postForEntity(url, multiValueMapHttpEntity, String.class);
        return JSON.parseObject(response.getBody(), new TypeReference<HealthLoginResult>() {
        });
    }
	
	// 获取数据接口方法
	 public String healthCheckDrugs(String orgname, Integer page) {
	        RestTemplate restTemplate = new RestTemplate();
	        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
	        HttpHeaders headers = new HttpHeaders();
	        HealthLoginResult loginResult = login();
	        if (loginResult == null) {
////	            log.error("healthCheckStatus 获取token失败");
	            return "11";
	        }
	        param.add("refresh_token", loginResult.getRefresh_token());
	        param.add("orgname", orgname);
	        param.add("page", page);
	        headers.set("Authorization", "Bearer " + loginResult.getAccess_token());
	        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
	        HttpEntity<MultiValueMap<String, Object>> multiValueMapHttpEntity = new HttpEntity<>(param, headers);
	        String url = "https://api.wx738.com/api/yOEeyfavNRJHAuZS1IgM4MYF6UBLoZb5";
	        try {
	            ResponseEntity<String> response = restTemplate.postForEntity(url, multiValueMapHttpEntity, String.class);
	            return response.getBody();
	        } catch (Exception e) {
	            e.printStackTrace();
	            return "22";
	        }
	 }
}
